package com.iwuyc.tools.commons.codec.type;

import com.iwuyc.tools.commons.codec.Codec;
import com.iwuyc.tools.commons.codec.TypeEnum;
import com.iwuyc.tools.commons.exception.IllegalFormatException;
import com.iwuyc.tools.commons.util.collection.ArrayUtil;

public class BooleanCodec implements Codec<Boolean> {
    @Override
    public Boolean decode(byte[] data) {
        final int length = ArrayUtil.arrayLength(data);
        if (length != 2) {
            throw new IllegalFormatException("data长度必须为2");
        }
        final byte flags = data[0];
        if (flags != TypeEnum.BOOLEAN.getFlags()) {
            throw new IllegalFormatException("data类型标识必须为" + TypeEnum.BOOLEAN.getFlags());
        }
        final byte content = data[1];
        return content == 1;
    }

    @Override
    public byte[] encode(Boolean data) {
        if (data == null) {
            throw new IllegalFormatException("data 不允许为null");
        }
        final byte content = data ? (byte) 1 : (byte) 0;
        return new byte[]{TypeEnum.BOOLEAN.getFlags(), content};
    }

    @Override
    public TypeEnum[] supportedTypes() {
        return new TypeEnum[]{TypeEnum.BOOLEAN};
    }
}
